package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.imgedit.utils.Matrix3;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.MosaicAdapter;
import flc.ast.bean.MyMosaicBean;
import flc.ast.databinding.ActivityPicMosaicBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;

public class PicMosaicActivity extends BaseAc<ActivityPicMosaicBinding> {

    public static String imgPath = "";
    private Bitmap myBitmap;
    private int paintWidth = 15;//画笔宽度
    private MosaicAdapter mosaicAdapter;
    private int oldPosition = 0;

    @Override
    protected int onCreate() {
        return R.layout.activity_pic_mosaic;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPicMosaicBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivPicMosaicSave.setOnClickListener(this);
        mDataBinding.ivImgInitial.setOnClickListener(this);
        mDataBinding.rvPicMosaicList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        mosaicAdapter = new MosaicAdapter();
        mDataBinding.rvPicMosaicList.setAdapter(mosaicAdapter);
        mosaicAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivImgInitial://原图
                mDataBinding.imageViewTouch.setImageBitmap(myBitmap);
                break;
            case R.id.ivPicMosaicSave://保存
                saveImg();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        mosaicAdapter.getItem(oldPosition).setSelect(false);
        mosaicAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        mosaicAdapter.getItem(position).setSelect(true);
        mosaicAdapter.notifyItemChanged(position);
        mDataBinding.mosaicPaintView.setMosaicBitmap(mosaicAdapter.getItem(position).getBitmap());
    }

    @Override
    protected void initData() {
        if (imgPath == null || TextUtils.isEmpty(imgPath)) return;
        myBitmap = ImageUtils.getBitmap(imgPath);
        mDataBinding.imageViewTouch.setImageBitmap(myBitmap);
        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        mDataBinding.imageViewTouch.setScaleEnabled(false);// 禁用缩放
        initPen();
        //马赛克数据
        List<MyMosaicBean> list = new ArrayList<>();
        list.add(new MyMosaicBean(ImageUtils.getBitmap(R.drawable.m1), R.drawable.m1, true));
        list.add(new MyMosaicBean(ImageUtils.getBitmap(R.drawable.m2), R.drawable.m2, false));
        list.add(new MyMosaicBean(ImageUtils.getBitmap(R.drawable.m3), R.drawable.m3, false));
        list.add(new MyMosaicBean(ImageUtils.getBitmap(R.drawable.m4), R.drawable.m4, false));
        list.add(new MyMosaicBean(ImageUtils.getBitmap(R.drawable.m5), R.drawable.m5, false));
        list.add(new MyMosaicBean(ImageUtils.getBitmap(R.drawable.m6), R.drawable.m6, false));
        mosaicAdapter.setList(list);
    }

    //初始化画笔
    private void initPen() {
        mDataBinding.mosaicPaintView.setWidth(paintWidth);
        mDataBinding.mosaicPaintView.setMosaicBitmap(ImageUtils.getBitmap(R.drawable.m1));
        //设置画笔大小
        mDataBinding.sbBrush.setMax(50);
        mDataBinding.sbBrush.setProgress(5);
        mDataBinding.sbBrush.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //画笔擦大小
                paintWidth = 5 + i * 2;
                mDataBinding.mosaicPaintView.setWidth(paintWidth);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    private void saveImg() {
        showDialog(getResources().getString(R.string.saving));
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                Matrix touchMatrix = mDataBinding.imageViewTouch.getImageViewMatrix();
                Bitmap retBitmap = Bitmap.createBitmap(myBitmap).copy(
                        Bitmap.Config.ARGB_8888, true);
                Canvas canvas = new Canvas(retBitmap);
                float[] data = new float[9];
                touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
                Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
                Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
                Matrix m = new Matrix();
                m.setValues(inverseMatrix.getValues());
                float[] f = new float[9];
                m.getValues(f);
                int dx = (int) f[Matrix.MTRANS_X];
                int dy = (int) f[Matrix.MTRANS_Y];
                float scale_x = f[Matrix.MSCALE_X];
                float scale_y = f[Matrix.MSCALE_Y];
                canvas.save();
                canvas.translate(dx, dy);
                canvas.scale(scale_x, scale_y);
                if (mDataBinding.mosaicPaintView.getPaintBit() != null) {
                    canvas.drawBitmap(mDataBinding.mosaicPaintView.getPaintBit(), 0, 0, null);
                }
                canvas.restore();
                //保存图片
                ImageUtils.save2Album(retBitmap, Bitmap.CompressFormat.PNG);
                emitter.onNext(true);
            }

            @Override
            public void accept(Boolean isSave) {
                dismissDialog();
                ToastUtils.showShort(R.string.save_success);
                startActivity(HomeActivity.class);
            }
        });
    }

}